package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.JPAHiberDAOFactory;
import dao.entity.ProductDAO;

import model.entity.OrderDetails;
import model.entity.product.Product;

/**
 * Servlet implementation class CartContr
 */
public class CartContr extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CartContr() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
	
	public static void addProductToCart(int idProduct, HttpSession session) {
		
		ArrayList<OrderDetails> cart = (ArrayList<OrderDetails>) session.getAttribute("cart");
		if(cart == null) cart = new ArrayList<OrderDetails>();
		
		OrderDetails detail = null;
		for (OrderDetails details : cart) {
			if(details.getProduct().getProductId() == idProduct)
			{
				detail = details;
				break;
			}
		}
		
		if(detail == null) {
			ProductDAO productDAO = JPAHiberDAOFactory.getInstance().getProductDAO();
			Product product = productDAO.findReference(idProduct);
			
			detail = new OrderDetails();
			detail.setProduct(product);
			detail.setQuantity(1);
			cart.add(detail);
			
		} else {
			detail.setQuantity(detail.getQuantity()+1);
		}
		
		session.setAttribute("cart", cart);
	}
	
	public static void removeProductToCart() {
		
	}

}
